<?php

namespace App\Supports\Payment\Methods\Sandwap;

use Exception;
use Carbon\Carbon;
use Brick\Math\RoundingMode;
use Illuminate\Support\Facades\Log;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodTransfer;

class TransferWithdraw extends Method implements MethodTransfer
{
	public function validate($object = null, $data = null) {}

	public function info($withdraw = null, $data = null)
	{
		$amount = big_decimal($withdraw->actual_amount)
			->toScale(2, RoundingMode::HALF_UP);
		$bankCard = $withdraw->bankCard;

		return [
			'orderCode'=>'withdraw_'.$withdraw->number,
			'version' => '01',
			'productId' => '00000004',
			'tranTime' => date('YmdHis', time()),
			'tranAmt' => '000000010000',
			'currencyCode' => '156',
            'accAttr' => '0',
            'accNo' => $bankCard->cert_number,
            'accType' => '4',
            'accName' => $bankCard->real_name,
            'bankName' => $bankCard->card_id,
            'remark' => 'pay', // 这个字段不要出现“代付”的字样
            'payMode' => '1',
            'channelType' => '07'
		];
	}

	public function transfer($withdraw = null, $data = null)
	{
		try {
			$info = $this->info($withdraw);
			$result = $this->channel->transfer($info);

			if ($result['status'] == 'SUCCESS') {
				$fee = $withdraw->user->preFreeWithdrawQuotaA($withdraw->target_amount);
				$withdraw->user()->update(['pre_free_withdraw_quota' => $fee]);
				$withdraw->update(['paid_at' => Carbon::now(), 'status' => 'paid']);
			} else {
				$withdraw->update(['paid_at' => Carbon::now(), 'status' => 'failed']);
			}
		} catch (Exception $exception) {
            $failedReason = $exception->getCode().$exception->getMessage();
			$withdraw->update(['remark' => "异常: {$failedReason}", 'status' => 'failed']);
		}
	}
}
